﻿using DotNetEx;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Mrc.Data;
using Mrc.Entity;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Mrc.Application.Middleware
{
    public class LoginInfoMiddleware
    {
        private readonly RequestDelegate _next;
        public LoginInfoMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public Task Invoke(HttpContext context)
        {
            string token = "";
            context.Items["islogin"] = false;
            AdminSession userSession = null;
            if (GlobalsConfig.cacheType == "redis")
            {
                if (context.Request.Cookies.TryGetValue("MRCTOKEN", out token))
                {
                    string userinfo = EncryptHelper.AESDecrypt(token, GlobalsConfig.EncryptKey);
                    string orginInfo = RedisHelper.Get(userinfo);
                    if (orginInfo.IsNullOrEmpty()) return this._next(context);
                    userSession = JsonHelper.Deserialize<AdminSession>(orginInfo);
                    context.Items["user"] = userSession;
                    context.Items["islogin"] = true;
                    //权限信息
                    if (userSession.AccountName.ToLower()=="admin")
                    {
                        context.Items["User_Permits"]= new List<string>();
                        return _next(context);
                    }
                    string Permisssions = RedisHelper.Get($"User_Permits:{userSession.UserId}");
                    if (Permisssions.IsNullOrEmpty())
                    {
                        ISysUserService userService = context.RequestServices.GetService(typeof(ISysUserService)) as ISysUserService;
                        List<string> userPermits = userService.GetUserPermits(userSession.UserId);
                        context.Items["User_Permits"] = userPermits;
                        RedisHelper.SetAsync($"User_Permits:{userSession.UserId}",userPermits.Serialize(), 180);//
                    }
                    else
                    {
                        context.Items["User_Permits"] = Permisssions.Deserialize<List<string>>();
                    }
                }
            }
            else
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    userSession = AdminSession.Parse(context.User);
                    if (userSession.AccountName.IsNullOrEmpty()) return this._next(context);
                    context.Items["user"] = userSession;
                    context.Items["islogin"] = true;
                    if (userSession.IsAdmin)
                    {
                        context.Items["User_Permits"] = new List<string>();
                    }
                    else
                    {
                        IMemoryCache cache = context.RequestServices.GetService(typeof(IMemoryCache)) as IMemoryCache;
                        List<string> userPermits = null;
                        cache.TryGetValue($"User_Permits:{userSession.UserId}", out userPermits);
                        if (userPermits == null)
                        {
                            ISysUserService userService = context.RequestServices.GetService(typeof(ISysUserService)) as ISysUserService;
                            userPermits = userService.GetUserPermits(userSession.UserId);
                            cache.Set<List<string>>($"User_Permits:{userSession.UserId}", userPermits, TimeSpan.FromMinutes(5));
                        }
                        context.Items["User_Permits"] = userPermits;
                    }
                }
            }
            return this._next(context);
        }
    }

    //请求中间件拓展
    public static partial class RequestMiddlewareExtensions
    {
        public static IApplicationBuilder UseWriteLoginInfo(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<LoginInfoMiddleware>();
        }
    }


}
